<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\PriDeviceInfo;
use App\Models\Phpwarn;

class AlarmController extends Controller {

    use \App\Http\Traits\UserPrivilege;

    public function index(Request $request) {
        
        $sid = $request->input('sid');
        
        $cid = $request->input('cid');
        
        $fields = [
            'pdi_devid', 'pdi_name', 'pdi_typememo', 'pdi_warnlevel', 
            'pdi_warnname', 'pdi_updatetime', 'pdi_areaid', 'pdi_areaname',
            'pdi_warnlevel', 'Co_ID'
        ];
        $lists = Phpwarn::select($fields)
            ->company($cid)
            ->site($sid)
            ->orderBy('pdi_updatetime', 'desc')
            ->get();
        $warns = $lists -> take(4);
        $warnLevel = $lists->groupBy('pdi_warnlevel')->map(function($item, $key){
            $config = config('device.warn_level');
            return [ 'lvl' => array_get($config, $key.'.name'), 'num' => count($item), 'plvl'=>$key];
        })->sortBy('plvl')->values();
        
        $user = $request->user();
        $groupField="pdi_devid";
        $deviceName="pdi_name";
        if($user->isSuperAdmin()){
            $groupField = "pdi_areaid";
            $deviceName="pdi_areaname";
        }
        $deviceWarn = $lists->groupBy($groupField)->map(function($item)use($deviceName){
            return [ 'device' => $item->first()->{$deviceName}, 'num' => count($item), "yunum"=>0];
        })->values();
 
        return [ 'devices' => $deviceWarn, 'warns'=>$warns, 'warnLevel'=>$warnLevel ];
        
    }

}
